package com.echo.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 数据库工具类，用于管理数据库连接
 * 使用基本的JDBC连接方式
 */
public class JdbcUtils {
    private static final Logger logger = Logger.getLogger(JdbcUtils.class.getName());
    private static String url;
    private static String username;
    private static String password;
    private static String driver;
    
    // 静态初始化块，加载配置
    static {
        try {
            // 加载db.properties配置文件
            Properties prop = new Properties();
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            prop.load(in);
            
            // 初始化连接参数
            url = prop.getProperty("jdbc.url");
            username = prop.getProperty("jdbc.username");
            password = prop.getProperty("jdbc.password");
            driver = prop.getProperty("jdbc.driver");
            
            // 加载驱动
            Class.forName(driver);
            logger.info("数据库驱动加载成功：" + driver);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "数据库初始化失败！", e);
            throw new RuntimeException("数据库初始化失败！", e);
        }
    }
    
    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = null;
        try {
            System.out.println("[JDBC] 尝试连接数据库: " + url);
            System.out.println("[JDBC] 用户名: " + username);
            
            // 直接使用DriverManager获取连接
            conn = DriverManager.getConnection(url, username, password);
            
            // 测试连接是否有效
            if (conn != null && !conn.isClosed()) {
                System.out.println("[JDBC] 数据库连接获取成功，连接状态: " + conn.isValid(5));
                // 设置自动提交为true（默认值）
                conn.setAutoCommit(true);
                System.out.println("[JDBC] 连接自动提交已设置为: " + conn.getAutoCommit());
            }
        } catch (SQLException e) {
            System.out.println("[JDBC ERROR] 获取数据库连接失败！错误码: " + e.getErrorCode());
            System.out.println("[JDBC ERROR] SQL状态: " + e.getSQLState());
            System.out.println("[JDBC ERROR] 错误消息: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
        return conn;
    }
    
    /**
     * 关闭数据库连接
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                if (!conn.isClosed()) {
                    conn.close();
                    logger.info("数据库连接已关闭");
                }
            } catch (SQLException e) {
                logger.log(Level.WARNING, "关闭数据库连接失败", e);
            }
        }
    }
    
    /**
     * 释放资源
     */
    public static void releaseResources(Connection conn, Statement stmt, ResultSet rs) {
        // 关闭结果集
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                logger.log(Level.WARNING, "关闭结果集失败", e);
            }
        }
        
        // 关闭语句
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                logger.log(Level.WARNING, "关闭语句失败", e);
            }
        }
        
        // 关闭连接
        closeConnection(conn);
    }
    
    /**
     * 关闭连接、预处理语句和结果集 (支持PreparedStatement)
     */
    public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        releaseResources(conn, pstmt, rs);
    }
    
    /**
     * 关闭连接和预处理语句 (不包含结果集)
     */
    public static void close(Connection conn, PreparedStatement pstmt) {
        releaseResources(conn, pstmt, null);
    }
    
    /**
     * 关闭连接和语句 (支持普通Statement)
     */
    public static void close(Connection conn, Statement stmt) {
        releaseResources(conn, stmt, null);
    }
    
    /**
     * 关闭连接、语句和结果集 (支持普通Statement)
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        releaseResources(conn, stmt, rs);
    }
}